package com.hange.ymcc.web.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import com.hange.ymcc.result.JSONResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@RestController
@RequestMapping("/oss")
public class OSSController {
    @RequestMapping("/sign")
    public JSONResult uploadFile(MultipartFile  fileName) throws ClientException {
        // Endpoint以华东1（杭州）为例，填写为https://oss-cn-beijing.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "hangetest";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-beijing。
        String region = "cn-beijing";

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 2. 上传文件
            //获取fileName的后缀
            String suffix = fileName.getOriginalFilename().substring(fileName.getOriginalFilename().lastIndexOf("."));

            //文件名称为日期 格式为 yyyy/MM/dd
            String date = new java.text.SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date());
            String objectName = date + "/" + System.currentTimeMillis() + suffix;

            ossClient.putObject(bucketName, objectName, fileName.getInputStream());
            System.out.println("文件 " + objectName + " 上传成功");

            String url = "https://"+bucketName+".oss-cn-beijing.aliyuncs.com/" + objectName;
            return JSONResult.success(url);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return JSONResult.error("上传失败");
    }

}
